package com.linktel.productionLine.EasyExcel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 通过自定义注解，给excel表头加上注释
 */
public class CommentCellWriteHandler implements CellWriteHandler {


    /**
     * 批注
     */
    private final Map<Integer, ExcelComment> notationMap;

    public CommentCellWriteHandler(Map<Integer, ExcelComment> notationMap) {
        this.notationMap = notationMap;
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 这里使用isHead判断 是否是表头的时候为true ,填入数据的时候是false , 之前使用head判断，调整表头备注只能有一个，切记
        if (isHead) {
            Sheet sheet = writeSheetHolder.getSheet();
            Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
            if (notationMap != null && notationMap.containsKey(cell.getColumnIndex())) {
                // 批注内容
                ExcelComment excelComment = notationMap.get(cell.getColumnIndex());
                if (Objects.nonNull(excelComment)) {
                    // 创建绘图对象
                    Comment comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), 0,
                            (short) cell.getColumnIndex() + (short) excelComment.getRemarkColumnWide(), (short) excelComment.getRemarkRowHigh()));
                    comment.setString(new XSSFRichTextString(excelComment.getRemarkValue()));
                    cell.setCellComment(comment);
                }

            }
        }
    }


}
